package db

import (
	"fmt"

	"github.com/linclaus/stock/pkg/model"
)

type UserManager interface {
	CreateUser(user *model.User) error
	DeleteUser(email string) error
	UpdateUserByEmail(email string) error
	GetUserByEmail(email string) (model.User, error)
}
type UserManagerImpl struct{}

func (u *UserManagerImpl) CreateUser(user *model.User) error {
	_, err := engine.Insert(user)
	if err != nil {
		fmt.Printf("create User failed for reason: %s\n", err)
	}
	return err
}

func (u *UserManagerImpl) UpdateUser(user *model.User) error {
	_, err := engine.ID(user.Id).Update(user)
	if err != nil {
		fmt.Printf("update User failed for reason: %s\n", err)
	}
	return err
}

func (u *UserManagerImpl) GetUserByEmail(email string) (model.User, error) {
	var user model.User
	_, err := engine.Where("email=?", email).Get(&user)
	if err != nil {
		fmt.Printf("get User failed for reason: %s\n", err)
	}
	return user, err
}

func (u *UserManagerImpl) UserEmailExist(email string) (bool, error) {
	return engine.Exist(&model.User{
		Email: email,
	})
}

func (u *UserManagerImpl) GetUserByOpenId(openId string) (model.User, error) {
	var user model.User
	_, err := engine.Where("open_id=?", openId).Get(&user)
	if err != nil {
		fmt.Printf("get User failed for reason: %s\n", err)
	}
	return user, err
}

func (u *UserManagerImpl) DeleteUser(user *model.User) error {
	_, err := engine.Delete(user)
	if err != nil {
		fmt.Printf("delete User: %d failed,for reason: %s", user.Id, err)
	}
	return err
}

var UserMgr = new(UserManagerImpl)
